<template>
  <div ref="editorRef"></div>
</template>

<script setup lang="ts">
import type { Editor } from 'tinymce'

const props = defineProps({
  /**
   * 是否自动初始化
   */
  autoInit: {
    type: Boolean,
    default: true
  }
})

const emits = defineEmits(['init'])

let VITE_TINYMCE_API_KEY = import.meta.env.VITE_TINYMCE_API_KEY

useHead({
  script: [
    {
      src: `https://cdn.tiny.cloud/1/${VITE_TINYMCE_API_KEY}/tinymce/7/tinymce.min.js`,
      referrerpolicy: 'origin',
      type: 'text/javascript'
    },
    // 加载富文本的语言包
    {
      src: '/langs/zh_CN.js',
      type: 'text/javascript'
    }
  ]
})

const editorRef = ref<HTMLElement>()
let editorInstance: Editor

const initEditor = async () => {
  if (!window.tinymce) {
    return
  }

  try {
    let eidtors = await window.tinymce.init({
      target: editorRef.value,
      plugins: 'lists link image table code help wordcount',
      language: 'zh_CN'
    })

    editorInstance = eidtors[0]

    editorInstance.on('init', (arg) => {})
  } catch (error) {
    console.log('初始化编辑器报错')
    console.log(error)
  }
}

const getInstance = () => {
  return editorInstance
}

defineExpose({
  getInstance,
  initEditor
})

onMounted(() => {
  if (props.autoInit) {
    initEditor()
  }
})
</script>
